import $ from 'jquery'

export default{
  state: {
    id: "",
    username: "",
    // photo: "",
    token: "",
    is_login: false,
    pulling_info: false,
  },
  getters: {
  },
  mutations: {
    updateUser(state, user) {
        state.id = user.id
        state.username = user.username
        // state.photo = user.photo
        state.is_login =  user.is_login
    },
    updateToken(state, token) {
        state.token = token
    },
    logout(state) {
        state.id = ""
        state.username = ""
        // state.photo = ""
        state.token = ""
        state.is_login = false
    },
    updatePullingInfo(state, pulling_info) {
        state.pulling_info = pulling_info
    }
  },
  actions: {
    login(context, data) {
        $.ajax({
            url: "http://127.0.0.1:8888/eshop/login",
            type: "post",
            contentType: 'application/json',
            data: JSON.stringify({
                account: data.account,
                password: data.password,
            }),
            success(resp) {
                context.commit("updateUser", {
                    account: data.account,
                    password: data.password,
                    is_login: true
                })
                if (resp.success === true) {
                    localStorage.setItem("jwt_token", resp.data)
                    context.commit("updateToken", resp.data)
                    data.success(resp)
                }
                else {
                    data.error(resp)
                }
            },
            error(resp) {
                data.error(resp)
            }
        })
    },
    logout(context) {
        localStorage.removeItem("jwt_token")
        context.commit("logout")
    },
    getinfo(context, data) {
        $.ajax({
            url: "http://127.0.0.1:8888/eshop/user",
            type: "get",
            headers: {
                Authorization: context.state.token
            },
            success(resp) {
                console.log(resp)
                if (resp.success === true) {
                    context.commit("updateUser", {
                        ...resp,
                        is_login: true
                    })
                    data.success(resp)
                }
                else {
                    data.error(resp)
                }
            },
            error(resp) {
                data.error(resp)
            }
        })
    }
  },
  modules: {
  }
}
